package com.sc.userspringboot.controller;

import com.alibaba.fastjson.JSON;
import com.sc.userspringboot.pojo.Users;
import com.sc.userspringboot.service.IUsersService;
import com.sc.userspringboot.utils.ResponseMsg;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sc.userspringboot.pojo.Users;
import com.sc.userspringboot.service.IUsersService;
import com.sc.userspringboot.utils.JwtUtils;
import com.sc.userspringboot.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户基础信息表 前端控制器
 * </p>
 *
 * @author user
 * @since 2025-09-19 06:27:31
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private IUsersService usersService;
    @GetMapping("/getUserById")
    public ResponseMsg getUserById(Integer id) {
        Users u = usersService.getById(id);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, u);
    }
    /**
     * 用户登录接口
     * @param user 包含email和password的用户对象
     * @return 登录结果和JWT token
     */
    @PostMapping("/login")
    ResponseMsg login(@RequestBody Users user) {
        // 检查请求参数是否为空
        if (user == null || user.getEmail() == null || user.getPassword() == null) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "邮箱和密码不能为空");
        }

        // 根据邮箱查找用户
        Users dbUser = usersService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Users>()
                        .eq("email", user.getEmail())
        );

        // 检查用户是否存在
        if (dbUser == null) {
            return ResponseMsg.getInstance(ResponseMsg.ACCOUNT_ERROR, "账号不存在");
        }

        // 验证密码（明文比较）
        if (!dbUser.getPassword().equals(user.getPassword())) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "密码错误");
        }

        // 更新最后登录时间
        dbUser.setLastLoginTime(new Date());
        usersService.updateById(dbUser);

        // 生成JWT token
        Map<String, Object> tokenData = new HashMap<>();
        tokenData.put("userId", dbUser.getUserId());
        tokenData.put("email", dbUser.getEmail());

        String token = JwtUtils.createJWT(
                String.valueOf(dbUser.getUserId()),
                com.alibaba.fastjson.JSON.toJSONString(tokenData),
                JwtUtils.JWT_EXPIRE_TIME // 7天过期
        );

        // 将token添加到Redis中
        JwtUtils.addToken(dbUser.getEmail(), token);

        // 返回成功响应和token
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("token", token);
        responseData.put("user", dbUser);

        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "登录成功", responseData);
    }
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public ResponseMsg getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "未提供Token");
        }

        token = token.substring(7); // 去掉 "Bearer "
        try {
            // 解析 token 获取用户信息
            Claims claims = JwtUtils.parseJWT(token);
            String subject = claims.getSubject();
            Map<String, Object> userInfo = JSON.parseObject(subject, Map.class);

            // 根据用户ID获取完整用户信息
            Integer userId = (Integer) userInfo.get("userId");
            Users user = usersService.getById(userId);

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "获取用户信息成功", user);
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "Token无效或已过期");
        }
    }

    /**
     * 用户注册接口
     * @param user 包含注册信息的用户对象
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseMsg register(@RequestBody(required = false) Users user) {
        // 检查请求参数是否为空
        if (user == null || user.getEmail() == null || user.getPassword() == null || user.getNickname() == null) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "邮箱、密码和昵称不能为空");
        }

        // 检查邮箱是否已存在
        Users existingUser = usersService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Users>()
                        .eq("email", user.getEmail())
        );

        if (existingUser != null) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "该邮箱已被注册");
        }

        // 设置注册时间
        user.setRegisterTime(new Date());
        user.setLastLoginTime(new Date());

        // 设置默认值
//        user.setLevel(1);
        user.setStatus((byte) 1); // 默认状态为正常
        user.setNotifySwitch((byte) 1); // 默认开启通知

        // 保存用户
        boolean saved = usersService.save(user);

        if (saved) {
            // 生成JWT token
            Map<String, Object> tokenData = new HashMap<>();
            tokenData.put("userId", user.getUserId());
            tokenData.put("email", user.getEmail());

            String token = JwtUtils.createJWT(
                    String.valueOf(user.getUserId()),
                    com.alibaba.fastjson.JSON.toJSONString(tokenData),
                    3600 * 24 * 1000 * 7 // 7天过期
            );

            // 将token添加到JwtUtils中
            JwtUtils.addToken(user.getEmail(), token);

            // 返回成功响应和token
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("user", user);

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "注册成功", responseData);
        } else {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "注册失败");
        }
    }
    @RequestMapping("/check")
    public ResponseMsg checkTokenValidity(HttpServletRequest request) {
        System.out.println("check");
        String token = request.getHeader("Authorization");
        System.out.println(token);
        if (token == null || !token.startsWith("Bearer ")) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "未提供Token");
        }

        token = token.substring(7); // 去掉 "Bearer "
        try {
            // 验证 token 是否有效
            Claims claims = JwtUtils.parseJWT(token);
            // 解析用户信息
            Users user = JSON.parseObject(claims.getSubject(), Users.class);
            // 检查Redis中token是否存在
            if (!JwtUtils.isAvailable(user.getEmail())) {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "Token已失效");
            }
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "Token有效");
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "Token无效或已过期");
        }
    }
}
